<template>
  <div class="message-container">
    <van-nav-bar title="留言模块" fixed placeholder left-arrow @click-left="handleBack" />

    <!-- 留言提交区域 -->
    <van-form class="form-card" @submit="handleSubmitMessage">
      <van-cell-group inset>
        <van-field
          v-model="newMessage.content"
          name="content"
          label="留言内容"
          type="textarea"
          placeholder="请输入您的留言..."
          autosize
          required
        />
      </van-cell-group>
      <div class="submit-btn">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="submitting"
        >
          提交留言
        </van-button>
      </div>
    </van-form>

    <!-- 留言历史展示区域 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多留言"
      @load="loadMessages"
    >
      <van-cell
        v-for="(message, index) in messageList"
        :key="index"
        :title="message.content"
        :value="`  ${message.createTime}`"
      />
    </van-list>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { addMessageService, messageListService } from '@/api/messages'
import { showToast } from 'vant'
import {useRouter} from 'vue-router'
const router = useRouter()
// 新留言数据
const newMessage = ref({
  content: '',
  userId: 6, // 假设当前用户ID为6，实际可从登录态获取
  createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
  status: 1,
  isDelete: 0
})
const submitting = ref(false)

// 留言列表数据
const messageList = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 加载留言历史
const loadMessages = async () => {
  if (finished.value) return
  loading.value = true

  const result = await messageListService(currentPage.value,pageSize.value)
  if (result.data.length < pageSize.value) {
    finished.value = true
  }
  messageList.value = [...messageList.value, ...result.data]
  currentPage.value++
  loading.value = false
}

// 提交留言
const handleSubmitMessage = async () => {
  if (!newMessage.value.content) {
    showToast('请输入留言内容')
    return
  }
  submitting.value = true
  const result = await addMessageService(newMessage.value.content)
  showToast(result.description || '留言提交成功')
  submitting.value = false
  // 重新加载留言列表
  messageList.value = []
  currentPage.value = 1
  finished.value = false
  loadMessages()
}

onMounted(() => {
  loadMessages()
})

// 处理返回按钮点击
const handleBack = () => {
  router.push('/workbenches')
  console.log('返回上一页')
}
</script>

<style scoped>
.message-container {
  background: #f5f7fa;
  min-height: 100vh;
}

.form-card {
  margin: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.submit-btn {
  padding: 16px;
}
</style>